package com.yitong.equipment.network

import com.blankj.utilcode.util.LogUtils
import com.yitong.equipment.entity.base.BaseRes
import io.reactivex.Observer
import io.reactivex.disposables.Disposable
import retrofit2.HttpException
import java.io.IOException
import java.net.ConnectException
import java.net.SocketTimeoutException
import java.util.concurrent.TimeoutException

class SubscriberCallBack<T : BaseRes<*>?>(private val apiCallback: ApiCallback<T>) : Observer<T> {
    override fun onError(e: Throwable) {
        e.printStackTrace()
        if (e is HttpException) {
            val httpException = e
            var msg = httpException.message
            val code = httpException.code()
            try {
                msg = httpException.response().toString()
            } catch (e1: IOException) {
                e1.printStackTrace()
            }
            msg = if (code == 408) {
                "服务器响应超时，请稍后再试。code=${code}msg=$msg"
            } else if (code == 405) {
                "请求行中指定的请求方法不能被用于请求相应的资源。code=${code}msg=$msg"
            } else if (code == 403) {
                "服务器已经理解请求，但是拒绝执行它。code=${code}msg=$msg"
            } else if (code == 500) {
                "服务器遇到了一个未曾预料的状况，导致了它无法完成对请求的处理。code=${code}msg=$msg"
            } else if (code == 404) {
                "请求失败，请求所希望得到的资源未被在服务器上发现。code=${code}msg=$msg"
            } else {
                "code=" + code + "msg=" + msg
            }
            apiCallback.onFailure(code, msg)
        } else if (e is SocketTimeoutException) {
            val msg = "连接服务器超时"
            apiCallback.onFailure(408, msg)
        } else if (e is ConnectException) {
            val msg = "网络中断，请检查您的网络状态"
            apiCallback.onFailure(408, msg)
        } else if (e is TimeoutException) {
            val msg = "连接超时，请检查您的网络状态"
            apiCallback.onFailure(408, msg)
        } else {
            LogUtils.d("netError", e.message)
            apiCallback.onFailure(0, "未知错误")
        }
        apiCallback.onCompleted()
    }


    override fun onSubscribe(disposable: Disposable) {
        apiCallback.onSubscribe(disposable)
    }

    override fun onNext(response: T) {
        apiCallback.onSuccess(response)
    }

    override fun onComplete() {
        apiCallback.onCompleted()
    }


}